<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-calendar"></i> 角色管理 </el-breadcrumb-item>
                <el-breadcrumb-item>角色修改</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="form-box">
                <el-form ref="form" :model="form" label-width="80px" :rules="rules">
                    <el-form-item label="角色名称" prop="name">
                        <el-input v-model="form.name"></el-input>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-switch v-model="form.status" :active-value="'01'" :inactive-value="'00'"></el-switch>
                    </el-form-item>
                    <el-form-item label="选择权限">
                        <el-cascader
                            v-model="selected1"
                            :options="options1"
                            :props="props"
                            clearable
                            @change="setPermissions"
                            ></el-cascader>
                    </el-form-item>

                    <el-form-item label="选择菜单">
                          <el-cascader
                            v-model="selected"
                            :options="options"
                            :props="props"
                            clearable
                            @change="setMenus"
                            ></el-cascader>
                    </el-form-item>

                    <el-form-item label="角色描述">
                        <el-input type="textarea" rows="5" v-model="form.description"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="goback" icon="el-icon-arrow-left">返回</el-button>
                        <el-button type="primary" @click="onSubmit('form')" icon="el-icon-edit">修改角色</el-button>
                        <el-button type="warning" @click="reset('form')" icon="el-icon-refresh-right">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'baseform',
    inject: ['reload'],
    data() {
        return {
            props: { multiple: true },
            id: this.$route.query.id,
            permissions: [],
            role:{},
            menus:[],
            options:[],
            options1:[],
            selected1:[],
            selected:[],
            types:[],
            form: {
                id: '',
                name: '',
                status: '01',
                permissions: [],
                menus:[],
                description: ''
            },
            user:{},
            condition: {
                name: '',
                status: '01'
            },
            
            rules: {
                name: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ]
            }
        };
    },
    created: function () {
        this.getType();
        this.initPers();
        this.init();
        this.getMenus();
        this.getLocalUser();
    },
    methods: {
        getLocalUser(){
            this.user = JSON.parse(window.sessionStorage.getItem("user"));
        },
        async init() {
            var d = await this.$http.get('/role/' + this.id);
            if ((d.code = 200)) {
                this.role = d.data;
                this.initForm(this.role);
                
                this.$message.success(d.message);
            } else {
                this.$message.error(d.message);
            }
        },

        initForm(role){
            this.form.id=this.id
            this.form.name=role.name
            this.form.status=role.status
            this.form.description=role.description
            this.initChecked(role.permissions)
            this.initSelcted(role.menus);
        },

        /**
         * 获取权限
         */
        async initPers() {
            var d = await this.$http.post('/permissionMap', this.condition);
            if ((d.code == 200)) {
                this.permissions = d.data;
                this.initOptions1();
            } else {
                this.$message.error(d.message);
            }
        },
         /**
         * 初始化权限选项
         */
        initOptions1(){
             for (let i = 0; i < this.types.length; i++) {
                 this.options1.push({
                     label: this.types[i].name,
                     value: this.types[i].code,
                     children: this.initPerByType(this.types[i].code)
                 })
            }
        },

        /**
         * 初始化权限选项
         */
        initPerByType(type){
            let c = [];
            for (let i = 0; i < this.permissions.length; i++) {
                if(this.permissions[i].type==type){
                    c.push({
                        label:this.permissions[i].name,
                        value:this.permissions[i].id,
                    })
                }
            }
            return c;
        },

        /**
         * 获取菜单列表
         */
        async getMenus(){
          var d = await this.$http.post("/menuMap",this.condition)
          if(d.code==200){
              this.menus=d.data;
              this.initOptions();
          } 
        },
        /**
         * 初始化菜单选项
         */
        initOptions(){
             for (let i = 0; i < this.menus.length; i++) {
             if (this.menus[i].level=='01') {
                 this.options.push({
                     value:this.menus[i].id,
                     label:this.menus[i].name,
                     children: this.initSecondMenu(this.menus[i].id)
                 })
             }
            }
        },
       
        /**
         * 初始化二级菜单
         */
        initSecondMenu(parentId){
            let c=[];
            for (let i = 0; i < this.menus.length; i++) {
                if (this.menus[i].level=='02' && this.menus[i].parentId==parentId) {
                    c.push({
                        value:this.menus[i].id,
                        label:this.menus[i].name
                    })
                }  
            }
            return c;
        },
        /**
         * 加工选中的id
         */
        setMenus(val){
            let ids=[];
            let f='';
            for (let  i= 0; i < val.length; i++) {
                if(f!=val[i][0]){
                    f=val[i][0]
                    ids.push(val[i][0])
                }
                ids.push(val[i][1]);
            }
           this.form.menus=ids;
        },
        /**
         * 加工选中的权限
         */
        setPermissions(val){
            this.form.permissions=[];
            for (let i = 0; i < val.length; i++) {
               this.form.permissions.push(val[i][1])
            }
        },

         getType() {
            this.types = JSON.parse(window.sessionStorage.getItem('type'));
        },

        initChecked(permissions) {
            this.selected1=[];
            for (let i = 0; i < permissions.length; i++) {
               this.selected1.push([permissions[i].type,permissions[i].id])
            }
            this.setPermissions(this.selected1);
        },

        initSelcted(menus){
            this.selected=[];
            let first=[];
            for (let i = 0; i < menus.length; i++) {
               if(menus[i].level=='01')
               {
                   first.push(menus[i])
               }
            }
            for (let i = 0; i < first.length; i++) {
               for (let a = 0; a < menus.length; a++) {
                  if( menus[a].level=='02' && menus[a].parentId==first[i].id ){
                      this.selected.push([first[i].id,menus[a].id])
                  }
               }
            }
            this.setMenus(this.selected)
        },

        onSubmit(formName) {
            this.form.id = this.id;
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    var d = await this.$http.put('/role', this.form);
                    if (d.code == 200) {
                         for (let i = 0; i < this.user.roles.length; i++) {
                             if (this.user.roles[i].id = this.id) {
                                 this.getUset();
                             }
                         }
                        this.$message.success(d.message);
                    } else {
                        this.$message.error(d.message);
                    }
                } else {
                    this.$message.warning('请把内容填写完整!');
                }
            });
        },

        async getUset(){
            var d = this.$http.get("/user/"+this.user.id)
            if (d.code==200) {
                window.sessionStorage.setItem("user",d.data);
            }
        },

        goback(){
            this.$router.go(-1);
        },

        reset(formName) {
            this.$confirm('此操作将重置所有信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.initForm(this.role);
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重置'
                    });
                });
        }
    }
};
</script>